package pers.hl.module_main.admin.book

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.common.base.ext.showMessage
import pers.hl.module_main.R
import pers.hl.module_main.common.LibLoadMoreModule
import pers.hl.module_main.common.PageHelper
import pers.hl.module_main.common.SwipeMenuHelper
import pers.hl.module_main.databinding.ActivityBookManageBinding
import pers.hl.module_main.search.BookAdapter

class BookManageActivity : BaseVBVMActivity<ActivityBookManageBinding, BookManageViewModel>() {

    private lateinit var loadMoreModule: LibLoadMoreModule
    private lateinit var bookAdapter: BookAdapter

    override fun initView(savedInstanceState: Bundle?) {
        initTitle()
        initRV()
        initLoadMore()
    }

    private fun initTitle() {
        mBinding.apply {
            titleBar.apply {
                tvBarTitle.text = "书籍管理"
                ivBarLeft.setOnClickListener {
                    finish()
                }
                ivBarRight.setImageResource(R.drawable.ic_add)
                ivBarRight.setOnClickListener {
                    showMessage("由用户自行分享")
                }
            }
        }
    }

    private fun initLoadMore() {
        loadMoreModule = LibLoadMoreModule(bookAdapter)
    }

    private fun initRV() {
        mBinding.apply {
            rvBook.apply {
                rvBook.layoutManager = LinearLayoutManager(this@BookManageActivity)
                bookAdapter = BookAdapter(mutableListOf(), true)
                initDeleteMenu()
            }
        }
    }

    private fun initDeleteMenu() {
        val menuCreator = SwipeMenuHelper.createDeleteItem(this)
        mBinding.rvBook.apply {
            setSwipeMenuCreator(menuCreator)
            setOnItemMenuClickListener { menuBridge, adapterPosition ->
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu()
                val deleteItem = bookAdapter.getItem(adapterPosition)
                val bookId = deleteItem.bookId
                bookId?.let {
                    mViewModel.deleteBook(it).observe(this@BookManageActivity, Observer {
                        getAll()
                    })
                }
            }
            adapter = bookAdapter
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        getAll()
    }

    private fun getAll() {
        mViewModel.getAllBooks().observe(this, Observer {
            bookAdapter.setList(it)
        })
    }

    override fun finishLoadMore() {
        loadMoreModule.loadMoreEnd(true)
    }

    override fun showLoading() {
        super.showLoading()
    }

    override fun hideLoading() {
        super.hideLoading()
    }


}